from django.contrib.auth import get_user_model
from django.conf import settings
from rest_framework import generics, permissions
from .serializers import UserSerializer, UserDetailSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

import itsdangerous


class UserCreateAPI(generics.CreateAPIView):
    """
    user register
    """

    model = get_user_model()
    serializer_class = UserSerializer


class UserExistAPI(APIView):
    """
    快速判断user是否已经存在
    0: no exist
    1: exist
    """

    def get(self, request, username):
        count = get_user_model().objects.filter(username=username).count()
        return Response({"count": count})


class MobileExistAPI(APIView):
    """
    快速判断mobile是否已经存在
    0: no exist
    1: exist
    """

    def get(self, request, mobile):
        count = get_user_model().objects.filter(mobile=mobile).count()
        return Response({"count": count})


# class UserLoginAPI(generics.RetrieveAPIView):
class UserLoginAPI(APIView):
    '''
    user login
    '''
    # queryset = get_user_model().objects.all()
    # serializer_class = UserSerializer

    def post(self, request, *args, **kwargs):
        print('1'*111)
        print(self.request.data)
        print(UserSerializer(get_user_model().objects.all()[0]))
        data = {'1': 'linux', '2': 'python'}
        # headers = {"Access-Control-Allow-Credentials": "true"}
        # return Response(data=data, headers=headers)
        return Response(data=data)

    def get(self, request, *args, **kwargs):
        print('2'*111)
        print(self.request.data)
        print(UserSerializer(get_user_model().objects.all()[0]))
        return Response({'1': 'linux', '2': 'python'})


class UserDetailAPI(generics.RetrieveAPIView, generics.UpdateAPIView):
    """
    user detail
    """
    serializer_class = UserDetailSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        return self.request.user


class UserEmailActivateAPI(APIView):
    def get(self, request, token):
        salt = settings.SECRET_KEY
        t = itsdangerous.TimedJSONWebSignatureSerializer(salt=salt, expires_in=3600, secret_key=salt)
        try:
            info = t.loads(token)
        except itsdangerous.exc.BadSignature:
            return Response({"result": "failed to activate"}, status=status.HTTP_401_UNAUTHORIZED)
        else:
            try:
                user = get_user_model().objects.get(username=info['username'])
                if user.email == info['email']:
                    user.email_activated = True
                    user.save()
                    return Response({'message': 'successfully activated'})
            except get_user_model().DoesNotExist:
                return Response({"result": "failed to activate"}, status=status.HTTP_401_UNAUTHORIZED)
